#include <stdio.h>
#include <stdarg.h>
#include "types.h"
#include "linkerset.h"
#include "app.h"
typedef void ( *COS_COMMAND_VAR )( va_list args );
CTD_LINKERSET_DECLARE( COMMAND_ITEM, COMMAND_ITEM* );

COS_COMMAND find_function( u8 group, u8 aid )
{
    COMMAND_ITEM* pitem = NULL;

    CTD_LINKERSET_FOREACH( COMMAND_ITEM, pitem )
    {
        printf( "Checking item: group_num = 0x%02x, func_aid = 0x%02x\n", pitem->group_num, pitem->func_aid );
        if ( ( pitem->group_num == group ) && ( pitem->func_aid == aid ) )
        {
            return pitem->pFunc; // 定位到函数，调用对应函数
        }
    }
    printf( "No match found for group_num = 0x%02x, func_aid = 0x%02x\n", group, aid );
    return NULL;
}

u8 function_run( u8 group, u8 aid, ... )
{
    COS_COMMAND_VAR pfunc = NULL;
    va_list         args;

    pfunc = find_function( group, aid );
    if ( pfunc != NULL )
    {
        va_start( args, aid );
        pfunc( args );
        va_end( args );
    }
    else
    {
        printf( "Function not found for group: 0x%02x, aid: 0x%02x\n", group, aid );
    }
    return 0;
}

u8 linkerset_test()
{
    u8 id = 1;
    u8 len = 1;
    u8 apdu_buffer[] = { 0x01, 0x02, 0x03, 0x04 };
    function_run( 1, 1, id, apdu_buffer );
    function_run( 1, 2 );
    function_run( 2, 1, id, len, apdu_buffer );

    // COS_COMMAND pfunc = NULL;
    // pfunc = find_function( 1, 1 );
    // pfunc( 1, NULL );
    // pfunc = find_function( 1, 2 );
    // pfunc();
    // pfunc = find_function( 2, 1 );
    // pfunc( 1, 1, NULL );
}


#include "ApiDef.h"
#include "origin_app.h"
API* pstAPI;
API  api;

u8 origin_apptest()
{

    pstAPI = &api;
    pstAPI->pRegister = Register;

    u8 aidBuffer[] = { 0x01, 0x02, 0x03 };
    u8 aidLengthS = sizeof( aidBuffer );

    RegisterFunction( aidBuffer, aidLengthS );
}

void app_test()
{
    linkerset_test();
    origin_apptest();
}

WEAK void app_init()
{
    // 初始化应用
    printf( "app init" );
    // 初始化全局变量

    // 测试应用
    app_test();
}
